import DetailsArticleAdopt from '@/pages/cues/components/DetailsArticleAdopt';
import { selectAdopt } from '@/services/api/api-cues-adopt';
import { adoptSubmit, getCuesSubmitDetails, scoreSubmit } from '@/services/api/api-cues-submit';
import { CheckCircleOutlined, DownloadOutlined } from '@ant-design/icons';
import { DrawerForm, ModalForm, ProFormDigit } from '@ant-design/pro-form';
import {
  Badge,
  Button,
  Descriptions,
  Divider,
  Image,
  Modal,
  Spin,
  Tag,
  Typography,
  Upload,
  UploadFile,
  message,
} from 'antd';
import React, { useState } from 'react';
import { useAccess } from 'umi';

interface DetailsSubmitProps {
  table: string;//table 使用位置  
  tableAdoptAccountId?: string | undefined;
  id: string | undefined;
  name: string | undefined;
  onRefurbish: () => void;
}

const DetailsSubmit: React.FC<DetailsSubmitProps> = ({ table, tableAdoptAccountId, id, name, onRefurbish }) => {
  const access = useAccess();

  const [details, setDetailsState] = useState<CuesSubmitData.SubmitDetails>();

  const [adoptDetails, setAdoptDetailsState] = useState<CuesAdoptData.AdoptForAccountVo>();


  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');

  const handleCancel = () => setPreviewOpen(false);

  /**
   * 获取 详情
   * @param key
   */
  const getSubmitDetails = async () => {
    try {
      const response = await getCuesSubmitDetails({ id });
      if (response.code === 0) {
        setDetailsState(response.data);
      }
    } catch (error) { }
  };

  /**
* 获取 该 用户 收录详情
* @param key
*/
  const getAdopt = async () => {
    try {
      const response = await selectAdopt({ articleId: id, adoptAccountId: tableAdoptAccountId, type: 2 });
      if (response.code === 0) {
        setAdoptDetailsState(response.data);
      }
    } catch (error) { }
  };


  const getFileNameFromUrl = (url: string) => {
    const hashIndex = url.indexOf('?');
    url = hashIndex !== -1 ? url.substring(0, hashIndex) : url;
    return (url.split('/').pop() || '').replace(/[\?].*$/g, '');
  };

  const handlePreview = async (file: UploadFile) => {
    console.log('======', file.url);
    setPreviewTitle(file.name);
    setPreviewImage(file.url);
    setPreviewOpen(true);
  };

  return (
    <DrawerForm
      key="details_details_drawer_form"
      title={details?.articleName}
      drawerProps={{
        // maskClosable: false,
        destroyOnClose: true,
      }}
      trigger={<a>{name}</a>}
      onVisibleChange={(visible) => {
        if (visible) {
          getSubmitDetails();
          if (table == "adopt") {
            getAdopt()
          }
        } else {
          onRefurbish();
        }
      }}
      submitter={
        details !== undefined &&
        (access.线索上报x选题计划x配置x管理员 || access.线索上报x选题计划x配置x需求者) && access.线索上报x主动报送x选题列表x收录线索 && {
          searchConfig: {
            submitText:
              details?.isInstructAdopt == 0
                ? details?.isSelfAdopt === 0
                  ? '录用'
                  : '取消录用'
                : false,
            resetText: '关闭',
          },
          render: (props, defaultDoms) => {
            return [
              ...defaultDoms,
              <ModalForm
                key={'score_record_modal_form'}
                layout={'horizontal'}
                title={
                  <>
                    <CheckCircleOutlined style={{ fontSize: '18px', color: '#87d068' }} />
                    <span
                      style={{
                        marginInlineStart: 10,
                      }}
                    >
                      请进行评分
                    </span>
                  </>
                }
                trigger={
                  <Button
                    hidden={
                      !(
                        access.线索上报x选题计划x配置x管理员 &&
                        access.线索上报x选题计划x选题列表x评分线索
                      )
                    }
                    type="primary"
                  >
                    评分
                  </Button>
                }
                autoFocusFirstInput
                modalProps={{
                  destroyOnClose: true,
                  width: '350px',
                }}
                initialValues={{
                  score: details?.score,
                }}
                submitTimeout={2000}
                onFinish={async (values) => {
                  const response = await scoreSubmit({ id, ...values });
                  if (response.code === 0) {
                    message.success('评分成功');
                    onRefurbish();
                    getSubmitDetails();
                    return true;
                  } else {
                    return true;
                  }
                }}
              >
                <ProFormDigit
                  width="md"
                  label="评分"
                  name="score"
                  min={0.01}
                  max={100}
                  fieldProps={{ precision: 2 }}
                  rules={[{ required: true, message: '请输入分值' }]}
                />
              </ModalForm>,
            ];
          },
        }
      }
      onFinish={async (values) => {
        const response = await adoptSubmit({ id });
        if (response.code === 0) {
          if (response.data.isAdopt === 0) {
            message.warning('取消收录');
          } else {
            message.success('收录成功');
          }
          onRefurbish();
          getSubmitDetails();
          return false;
        } else {
          return false;
        }
      }}
    >
      <Spin
        style={{
          textAlign: 'center',
        }}
        spinning={details === undefined}
      >
        {access.线索上报x选题计划x配置x管理员 && access.线索上报x选题计划x选题列表x评分线索 && (
          <Descriptions>
            <Descriptions.Item label="评分">{details?.score}</Descriptions.Item>
          </Descriptions>
        )}
        <Descriptions>
          {access.线索上报x选题计划x配置x需求者 &&
            access.线索上报x选题计划x选题列表x收录线索 &&
            (access.线索上报x选题计划x配置x管理员 ? (
              <>
                <Descriptions.Item label="是否录用">
                  {details?.isAdopt === 0 ? '否' : '是'}
                </Descriptions.Item>
                <Descriptions.Item label="是否自己录用">
                  {details?.isSelfAdopt === 0 ? '否' : '是'}
                </Descriptions.Item>
              </>
            ) : (
              <Descriptions.Item label="是否录用">
                {details?.isSelfAdopt === 0 ? '否' : '是'}
              </Descriptions.Item>
            ))}
          <Descriptions.Item label="录用次数">
            {access.线索上报x选题计划x配置x提供者管理员 && access.线索上报x主动报送x选题列表x收录线索 ? <Badge
              count={details?.countAdopt}
              style={{
                marginInlineStart: 4,
                color: '#1890FF',
                backgroundColor: '#E6F7FF',
              }}
            /> : <DetailsArticleAdopt
              type={1}
              articleId={details?.id}
              count={details?.countAdopt}
              onRefurbish={function (): void {
                onRefurbish();
                getSubmitDetails();
                if (table == "adopt") {
                  getAdopt()
                }
              }}
            />
            }


          </Descriptions.Item>
        </Descriptions>
        <Divider />
        <Descriptions>
          <Descriptions.Item label="选题主题">{details?.topicName}</Descriptions.Item>
        </Descriptions>
        <Descriptions>
          <Descriptions.Item label="选题计划">{details?.topicPlanName}</Descriptions.Item>
        </Descriptions>
        <Descriptions>
          <Descriptions.Item label="创建组织">{details?.topicOrganizationName}</Descriptions.Item>
        </Descriptions>
        <Divider />
        <Descriptions>
          <Descriptions.Item label="上报组织">{details?.articleOrganizationName}</Descriptions.Item>
          <Descriptions.Item label="上报人">{details?.articleAccountName}</Descriptions.Item>
          <Descriptions.Item label="联系方式">{details?.articleAccountPhone}</Descriptions.Item>
          <Descriptions.Item label="上报时间">{details?.createdTime}</Descriptions.Item>
        </Descriptions>
        <Descriptions>
          <Descriptions.Item label="行业">
            <Tag>{details?.articleIndustryName}</Tag>
          </Descriptions.Item>
        </Descriptions>
        <Descriptions>
          <Descriptions.Item label="标签">
            {details?.articleLabels.map((item) => {
              return <Tag key={item}>{item}</Tag>;
            })}
          </Descriptions.Item>
        </Descriptions>
        {details?.remarks && (
          <Typography.Paragraph>
            备注
            <blockquote>{details?.remarks}</blockquote>
          </Typography.Paragraph>
        )}

        {table == "adopt" && adoptDetails && <>
          <Divider />
          <Typography.Title level={5}>
            {adoptDetails.isInstruct === 0 && adoptDetails.cancelAccountId && <Tag color='red'>
              取消
            </Tag>}
            <Tag color={adoptDetails?.isInstruct === 0 ? 'green' : 'orange'}>
              {adoptDetails?.isInstruct === 0 ? '自主' : '指令'}
            </Tag>
            {adoptDetails?.organizationName} - {adoptDetails?.accountName}
          </Typography.Title>
          <Typography.Paragraph>
            {adoptDetails?.isInstruct === 1 && (
              <blockquote>指令人：{adoptDetails?.instructAccountName}</blockquote>
            )}
            {adoptDetails?.instructDescribes != null && adoptDetails?.instructDescribes != "" && (
              <blockquote>指令描述：{adoptDetails?.instructDescribes}</blockquote>
            )}
            <blockquote>收录时间：{adoptDetails?.createdTime}</blockquote>
            {adoptDetails.isInstruct === 0 && adoptDetails.cancelAccountId && (
              <><blockquote>取消人：{adoptDetails.cancelAccountName}</blockquote>
                <blockquote>取消时间：{adoptDetails.cancelTime}</blockquote>
                <blockquote>取消描述：{adoptDetails.cancelDescribes}</blockquote></>
            )}
          </Typography.Paragraph>
        </>}
        <Divider />
        <Typography.Title level={3} style={{ textAlign: 'center' }}>
          {details?.articleName}
        </Typography.Title>
        <br />
        <div
          dangerouslySetInnerHTML={{
            __html: `${details?.articleContent}`,
          }}
        />
        {details?.articleAttachments && details?.articleAttachments.length > 0 && (
          <>
            <Divider />
            <div
              style={{
                textAlign: 'right',
              }}
            >
              <Button
                type="primary"
                key="import"
                size="small"
                icon={<DownloadOutlined />}
                onClick={() => {
                  details?.articleAttachments.forEach(function (item) {
                    window.open(item.content, '_blank');
                  });
                }}
              >
                全部下载
              </Button>
            </div>

            <Upload
              listType="picture"
              multiple
              fileList={details?.articleAttachments.map((item) => {
                return {
                  uid: item.id,
                  name: getFileNameFromUrl(item.content),
                  url: item.content,
                  status: 'done',
                };
              })}
              showUploadList={{
                downloadIcon: (
                  <div style={{ marginLeft: '-100px', padding: '17px 0', marginTop: '-15px' }}>
                    <DownloadOutlined
                      style={{
                        marginRight: '10px',
                      }}
                    />
                    点击下载
                  </div>
                ),
                showRemoveIcon: false,
                showDownloadIcon: true,
              }}
              onPreview={handlePreview}
            />
            <Modal open={previewOpen} title={previewTitle} footer={null} onCancel={handleCancel}>
              <Image width="100%" src={previewImage} />
            </Modal>
          </>
        )}
      </Spin>
    </DrawerForm>
  );
};

export default DetailsSubmit;
